// pages/signature/index.js
Page({
  data: {
    contractId: '', // 合同ID
    flow: 'landlord', // 流程类型
    formData: {
      name: '',
      idCard: '',
      phone: '',
      address: '',
      emergencyContact: '',
      emergencyPhone: ''
    },
    contractData: {}, // 合同数据
    signatureImage: '',
    showSignature: false,
    ctx: null,
    canvasWidth: 0,
    canvasHeight: 0,
    points: []
  },

  async onLoad(options) {
    // 获取系统信息，用于设置画布大小
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          canvasWidth: res.windowWidth,
          canvasHeight: res.windowHeight - 120 // 减去头部高度
        });
      }
    });
    
    // 记录流程类型
    const flow = options.flow || 'landlord';
    this.setData({ flow: flow });
    
    // 如果是租客流程，通过合同ID加载
    if (flow === 'tenant' && options.contractId) {
      this.setData({ contractId: options.contractId });
      await this.loadContractData();
    } else if (options.data) {
      // 房东流程，接收合同数据
      try {
        const contractData = JSON.parse(decodeURIComponent(options.data));
        this.setData({
          contractData: contractData
        });
        console.log('合同数据已加载:', contractData);
        
        // 如果合同数据中有租客信息，预填充表单
        if (contractData.tenantName) {
          this.setData({
            'formData.name': contractData.tenantName
          });
        }
        if (contractData.tenantPhone) {
          this.setData({
            'formData.phone': contractData.tenantPhone
          });
        }
      } catch (e) {
        console.error('解析合同数据失败:', e);
      }
    }

    await this.loadUserInfo();
  },
  // 加载用户信息用于预填表单
  async loadUserInfo() {
    try {
      const res = await wx.cloud.callFunction({
        name: 'user',
        data: {
          apiType: 'getUserInfo'
        }
      });

      if (res.result && res.result.res && res.result.res.code === 200) {
        const userInfo = res.result.res.data || {};
        const formData = this.data.formData;
        const updates = {};

        if (!formData.name && userInfo.name) {
          updates['formData.name'] = userInfo.name;
        }
        if (!formData.idCard && (userInfo.idCard || userInfo.identityCard)) {
          updates['formData.idCard'] = userInfo.idCard || userInfo.identityCard;
        }
        if (!formData.phone && (userInfo.phone || userInfo.mobile)) {
          updates['formData.phone'] = userInfo.phone || userInfo.mobile;
        }
        if (!formData.address && userInfo.address) {
          updates['formData.address'] = userInfo.address;
        }
        if (!formData.emergencyContact && (userInfo.emergencyContact || userInfo.emergencyContactName)) {
          updates['formData.emergencyContact'] = userInfo.emergencyContact || userInfo.emergencyContactName;
        }
        if (!formData.emergencyPhone && (userInfo.emergencyPhone || userInfo.emergencyContactPhone)) {
          updates['formData.emergencyPhone'] = userInfo.emergencyPhone || userInfo.emergencyContactPhone;
        }

        if (Object.keys(updates).length > 0) {
          this.setData(updates);
        }
      }
    } catch (error) {
      console.error('加载用户信息失败:', error);
    }
  },

  
  // 加载合同数据（租客流程）
  async loadContractData() {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    
    try {
      const res = await wx.cloud.callFunction({
        name: 'contract',
        data: {
          apiType: 'getContractInfo',
          contractId: this.data.contractId
        }
      });

      wx.hideLoading();

      if (res.result.res.code === 200) {
        const contractData = res.result.res.data;
        this.setData({
          contractData: contractData
        });
        
        // 预填充表单数据
        if (contractData.tenantName) {
          this.setData({
            'formData.name': contractData.tenantName
          });
        }
        if (contractData.tenantPhone) {
          this.setData({
            'formData.phone': contractData.tenantPhone
          });
        }
        if (contractData.tenantIdCard) {
          this.setData({
            'formData.idCard': contractData.tenantIdCard
          });
        }
        if (contractData.tenantAddress) {
          this.setData({
            'formData.address': contractData.tenantAddress
          });
        }
        if (contractData.emergencyContact) {
          this.setData({
            'formData.emergencyContact': contractData.emergencyContact
          });
        }
        if (contractData.emergencyPhone) {
          this.setData({
            'formData.emergencyPhone': contractData.emergencyPhone
          });
        }
        if (contractData.tenantSignature) {
          this.setData({
            signatureImage: contractData.tenantSignature
          });
        }
        
        console.log('合同数据已加载:', contractData);
      } else {
        wx.showToast({
          title: res.result.res.msg || '加载失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('加载合同数据失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: '加载失败，请重试',
        icon: 'none'
      });
    }
  },

  // 表单输入事件
  onNameInput(e) {
    this.setData({
      'formData.name': e.detail.value
    });
  },

  onIdCardInput(e) {
    this.setData({
      'formData.idCard': e.detail.value
    });
  },

  onPhoneInput(e) {
    this.setData({
      'formData.phone': e.detail.value
    });
  },

  onEmergencyContactInput(e) {
    this.setData({
      'formData.emergencyContact': e.detail.value
    });
  },

  onEmergencyPhoneInput(e) {
    this.setData({
      'formData.emergencyPhone': e.detail.value
    });
  },

  onAddressInput(e) {
    this.setData({
      'formData.address': e.detail.value
    });
  },

  // 打开签名画布
  openSignature() {
    this.setData({
      showSignature: true,
      points: []
    });

    // 初始化画布
    setTimeout(() => {
      const ctx = wx.createCanvasContext('signatureCanvas', this);
      ctx.setStrokeStyle('#000000');
      ctx.setLineWidth(3);
      ctx.setLineCap('round');
      ctx.setLineJoin('round');
      this.setData({ ctx });
    }, 100);
  },

  // 关闭签名画布
  closeSignature() {
    this.setData({
      showSignature: false
    });
  },

  // 阻止滚动
  preventMove() {
    return false;
  },

  // 触摸开始
  onTouchStart(e) {
    const { x, y } = e.touches[0];
    const ctx = this.data.ctx;
    if (!ctx) return;

    this.data.points = [{ x, y }];
    
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.stroke();
    ctx.draw(true);
  },

  // 触摸移动
  onTouchMove(e) {
    const { x, y } = e.touches[0];
    const ctx = this.data.ctx;
    if (!ctx) return;

    const points = this.data.points;
    if (points.length > 0) {
      const lastPoint = points[points.length - 1];
      ctx.moveTo(lastPoint.x, lastPoint.y);
      ctx.lineTo(x, y);
      ctx.stroke();
      ctx.draw(true);
    }

    this.data.points.push({ x, y });
  },

  // 触摸结束
  onTouchEnd(e) {
    // 可以在这里做额外的处理
  },

  // 清除签名
  clearSignature() {
    const ctx = this.data.ctx;
    if (!ctx) return;

    ctx.clearRect(0, 0, this.data.canvasWidth, this.data.canvasHeight);
    ctx.draw(true);
    this.setData({
      points: []
    });
  },

  // 保存签名
  saveSignature() {
    const ctx = this.data.ctx;
    if (!ctx) return;

    // 检查是否有签名内容
    if (this.data.points.length === 0) {
      wx.showToast({
        title: '请先签名',
        icon: 'none'
      });
      return;
    }

    // 确保画布绘制完成
    ctx.draw(true);
    
    // 延迟一下确保绘制完成后再导出
    setTimeout(() => {
      // 将画布内容转换为图片
      wx.canvasToTempFilePath({
        canvasId: 'signatureCanvas',
        success: (res) => {
          this.setData({
            signatureImage: res.tempFilePath,
            showSignature: false
          });
          wx.showToast({
            title: '签名保存成功',
            icon: 'success'
          });
        },
        fail: (err) => {
          console.error('保存签名失败', err);
          wx.showToast({
            title: '保存失败，请重试',
            icon: 'none'
          });
        }
      }, this);
    }, 100);
  },

  // 下一步：保存信息并跳转到合同页面
  async goToNext() {
    const { formData, contractId } = this.data;

    // 表单验证
    if (!formData.name || !formData.name.trim()) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return;
    }

    if (!formData.idCard || !formData.idCard.trim()) {
      wx.showToast({
        title: '请输入身份证号',
        icon: 'none'
      });
      return;
    }

    if (!formData.phone || !formData.phone.trim()) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      });
      return;
    }

    // 验证身份证号格式（简单验证）
    const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (!idCardReg.test(formData.idCard)) {
      wx.showToast({
        title: '请输入正确的身份证号',
        icon: 'none'
      });
      return;
    }

    // 验证手机号格式
    const phoneReg = /^1[3-9]\d{9}$/;
    if (!phoneReg.test(formData.phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '保存中...',
      mask: true
    });

    try {
      // 更新合同中的租客信息
      if (contractId) {
        const res = await wx.cloud.callFunction({
          name: 'contract',
          data: {
            apiType: 'updateContractTenantContact',
            contractId: contractId,
            tenantName: formData.name,
            tenantPhone: formData.phone,
            tenantIdCard: formData.idCard,
            tenantAddress: formData.address || '',
            emergencyContact: formData.emergencyContact || '',
            emergencyPhone: formData.emergencyPhone || ''
          }
        });

        wx.hideLoading();

        if (res.result.res.code === 200) {
          // 跳转到合同页面
          wx.navigateTo({
            url: `/pages/contract/index?contractId=${contractId}&flow=tenant`
          });
        } else {
          throw new Error(res.result.res.msg || '保存失败');
        }
      } else {
        wx.hideLoading();
        wx.showToast({
          title: '合同ID不存在',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('保存信息失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: error.message || '保存失败，请重试',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 提交合同（已废弃，保留以防万一）
  async submitContract() {
    const { formData, signatureImage: tenantSignatureTempPath, contractData } = this.data;

    // 表单验证
    if (!formData.name || !formData.name.trim()) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return;
    }

    if (!formData.idCard || !formData.idCard.trim()) {
      wx.showToast({
        title: '请输入身份证号',
        icon: 'none'
      });
      return;
    }

    if (!formData.phone || !formData.phone.trim()) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      });
      return;
    }

    if (!tenantSignatureTempPath) {
      wx.showToast({
        title: '请先签名',
        icon: 'none'
      });
      return;
    }

    // 验证身份证号格式（简单验证）
    const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (!idCardReg.test(formData.idCard)) {
      wx.showToast({
        title: '请输入正确的身份证号',
        icon: 'none'
      });
      return;
    }

    // 验证手机号格式
    const phoneReg = /^1[3-9]\d{9}$/;
    if (!phoneReg.test(formData.phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '提交中...',
      mask: true
    });

    try {
      // 上传签名图片到云存储
      let signatureUrl = '';
      if (tenantSignatureTempPath) {
        const fileExtension = tenantSignatureTempPath.split('.').pop();
        const cloudPath = `signatures/${Date.now()}-${Math.random().toString(36).substr(2, 9)}.${fileExtension}`;
        const uploadRes = await wx.cloud.uploadFile({
          cloudPath: cloudPath,
          filePath: tenantSignatureTempPath
        });
        signatureUrl = uploadRes.fileID;
      }

      // 更新合同数据中的租客信息
      const updatedContractData = {
        ...contractData,
        tenantName: formData.name,
        tenantPhone: formData.phone,
        tenantIdCard: formData.idCard,
        tenantAddress: formData.address || '',
        emergencyContact: formData.emergencyContact || '',
        emergencyPhone: formData.emergencyPhone || '',
        tenantSignature: signatureUrl,
        signedAt: new Date().toISOString()
      };

      // 更新合同中的租客信息和签名
      if (this.data.contractId) {
        // 调用云函数更新合同（租客签约）
        const res = await wx.cloud.callFunction({
          name: 'contract',
          data: {
            apiType: 'updateContractTenantSignature',
            contractId: this.data.contractId,
            tenantName: formData.name,
            tenantPhone: formData.phone,
            tenantIdCard: formData.idCard,
            tenantAddress: formData.address || '',
            emergencyContact: formData.emergencyContact || '',
            emergencyPhone: formData.emergencyPhone || '',
            tenantSignature: signatureUrl
          }
        });

        if (res.result.res.code === 200) {
          wx.hideLoading();
          wx.showToast({
            title: '签名保存成功',
            icon: 'success'
          });

          // 返回合同页面（显示签字图片）
          setTimeout(() => {
            wx.navigateBack({
              delta: 1 // 返回到合同页面
            });
          }, 500);
        } else {
          throw new Error(res.result.res.msg || '保存失败');
        }
      } else {
        // 如果没有合同ID，可能是直接签约流程
        wx.hideLoading();
        wx.showToast({
          title: '签名保存成功',
          icon: 'success'
        });

        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 500);
      }
    } catch (error) {
      console.error('提交合同失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: error.message || '提交失败，请重试',
        icon: 'none',
        duration: 2000
      });
    }
  }
});
